use std::{vec};
use tokio::net::{TcpStream};
use tokio::{sync::mpsc};

#[tokio::main]
async fn main() {
    // let mut routes = vec![];
    let mut ports = vec![];
    let (tx,mut rx) = mpsc::channel(10);
    let now = std::time::Instant::now();
    for _p in 21..65536{
        let tx = tx.clone();
       let _j = tokio::spawn(async move {
            let addr = format!("192.168.1.17:{}",_p);
            // println!("{}",addr);
            let socket = TcpStream::connect(addr).await;
            if socket.is_err(){
                // println!("port is {} idle",_p);
                // tx.send(None).await.unwrap();
            }else{
                //println!("port is {} busy",_p);
                tx.send(Some(_p)).await.unwrap();
            }
            // drop(tx);
        });
        // routes.push(j);
    }
    //没有这句话，就结束不了
    drop(tx);
    //
    // for _p in routes{
    //     _p.await.unwrap();
    // }
    //
    // drop(tx);
    //
    // for v in rx.recv().await{
    //     if let Some(_p) = v{
    //         //  println!("port is {} busy",_p);
    //         ports.push(_p);
    //     }
    // }
    while let Some(t) = rx.recv().await{
        // println!("{:?}",t);
        if let Some(_p) = t{           
            ports.push(_p);
        }      
    }
    //
    ports.sort_unstable();
    let end = now.elapsed().as_secs_f64();
    //写入结果到文件
    for _p in ports{
        println!("{}:{}","192.168.1.17",_p);
    }
    println!("elapsed {}s",end);
    //
    // println!("{:?},{}",ports,end);
    // let mut _s = String::new();
    // stdin().read_line(&mut _s).unwrap();
}

